#include "htf_resource_manager.h"
#include "../utils/htf_crypto.h"
#include "../utils/htf_secure_mem.h"
#include "../utils/htf_logger.h"
#include <stdio.h>
#include <stdlib.h>

htf_resource_t* htf_load_resource_secure(const char* path, const uint8_t* key, size_t key_len) {
    FILE* f = fopen(path, "rb");
    if (!f) {
        HTF_LOG_ERROR("Cannot open %s", path);
        return NULL;
    }

    fseek(f, 0, SEEK_END);
    size_t enc_size = ftell(f);
    fseek(f, 0, SEEK_SET);

    uint8_t* enc_buf = (uint8_t*)malloc(enc_size);
    if (!enc_buf) {
        fclose(f);
        return NULL;
    }

    fread(enc_buf, 1, enc_size, f);
    fclose(f);

    uint8_t* plain = NULL;
    size_t plain_sz = 0;
    if (htf_crypto_decrypt(enc_buf, enc_size, key, key_len, &plain, &plain_sz) != 0) {
        free(enc_buf);
        HTF_LOG_ERROR("Decryption failed for %s", path);
        return NULL;
    }
    free(enc_buf);

    htf_resource_t* res = (htf_resource_t*)htf_secure_calloc(1, sizeof(htf_resource_t));
    if (!res) {
        htf_secure_free(plain);
        return NULL;
    }

    res->data = plain;
    res->size = plain_sz;
    res->is_secure = 1;
    return res;
}

void htf_release_resource(htf_resource_t* res) {
    if (!res) return;
    if (res->is_secure) {
        htf_secure_memzero(res->data, res->size);
        free(res->data);
    } else {
        free(res->data);
    }
    htf_secure_free(res);
}